package com.baidu.iit.pxp.el.juel.ast;

import com.baidu.iit.pxp.el.ELContext;
import com.baidu.iit.pxp.el.ELException;
import com.baidu.iit.pxp.el.juel.Bindings;

/**
 * User: huangweili
 * Date: 14-4-29
 * Time: 下午4:50
 */
public class AstChoice extends AstRightValue {
    private final AstNode question, yes, no;

    public AstChoice(AstNode question, AstNode yes, AstNode no) {
        this.question = question;
        this.yes = yes;
        this.no = no;
    }

    @Override
    public Object eval(Bindings bindings, ELContext context) throws ELException {
        Boolean value = bindings.convert(question.eval(bindings, context), Boolean.class);
        return value.booleanValue() ? yes.eval(bindings, context) : no.eval(bindings, context);
    }

    @Override
    public String toString() {
        return "?";
    }

    @Override
    public void appendStructure(StringBuilder b, Bindings bindings) {
        question.appendStructure(b, bindings);
        b.append(" ? ");
        yes.appendStructure(b, bindings);
        b.append(" : ");
        no.appendStructure(b, bindings);
    }

    public int getCardinality() {
        return 3;
    }

    public AstNode getChild(int i) {
        return i == 0 ? question : i == 1 ? yes : i == 2 ? no : null;
    }
}
